﻿@inject ILogger<Edit> Logger
@inject IJSRuntime JSRuntime
@inject IUserManagementService UserManagementService
@inject IRoleManagementService RoleManagementService

@inherits BlazorAdmin.Helpers.BlazorComponent

@namespace BlazorAdmin.Pages.UserPage
@using BlazorAdmin.Interfaces
@using BlazorAdmin.Models
@using Microsoft.AspNetCore.Identity

<div class="modal @_modalClass" tabindex="-1" role="dialog" style="display:@_modalDisplay">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            @if (_item == null)
            {
                <Spinner></Spinner>
            }
            else
            {
                <EditForm Model="_item" OnValidSubmit="@SaveClick">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Edit @_item.UserName</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close" @onclick="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="container">
                            <div class="row">
                                <div class="col-md-12">
                                    <!-- User Information -->
                                    <div class="form-group row">
                                        <label for="UserName" class="control-label col-md-6">Username</label>
                                        <div class="col-md-6">
                                            <InputText id="UserName" class="form-control" @bind-Value="_item.UserName" />
                                            <ValidationMessage For="@(() => _item.UserName)" class="text-danger" />
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="Email" class="control-label col-md-6">Email</label>
                                        <div class="col-md-6">
                                            <InputText id="Email" class="form-control" @bind-Value="_item.Email" />
                                            <ValidationMessage For="@(() => _item.Email)" class="text-danger" />
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="PhoneNumber" class="control-label col-md-6">Phone Number</label>
                                        <div class="col-md-6">
                                            <InputText id="PhoneNumber" class="form-control" @bind-Value="_item.PhoneNumber" />
                                            <ValidationMessage For="@(() => _item.PhoneNumber)" class="text-danger" />
                                        </div>
                                    </div>

                                    <div class="form-group row form-check">
                                        <div class="col-md-6">
                                            <InputCheckbox id="EmailConfirmed" class="form-check-input" @bind-Value="_item.EmailConfirmed" />
                                            <label for="EmailConfirmed" class="form-check-label">Email Confirmed</label>
                                        </div>
                                    </div>

                                    <div class="form-group row form-check">
                                        <div class="col-md-6">
                                            <InputCheckbox id="TwoFactorEnabled" class="form-check-input" @bind-Value="_item.TwoFactorEnabled" />
                                            <label for="TwoFactorEnabled" class="form-check-label">Two-Factor Authentication Enabled</label>
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="LockoutEnd" class="control-label col-md-6">Lockout Until</label>
                                        <div class="col-md-6">
                                            <InputDate id="LockoutEnd" class="form-control" @bind-Value="_item.LockoutEnd" />
                                            <ValidationMessage For="@(() => _item.LockoutEnd)" class="text-danger" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <h4>Roles</h4>
                        @if (_roles == null || _roles.Count == 0)
                        {
                            <p>No roles available.</p>
                        }
                        else
                        {
                            @foreach (var role in _roles)
                            {
                                <div class="form-group row form-check">
                                    <div class="col-md-6">
                                        <input type="checkbox" id="@role" class="form-check-input" checked="@_selectedRoles[role.Name]" @onchange="(e) => UpdateRoleSelectedState(role.Name, (bool)((ChangeEventArgs)e).Value)" />
                                        <label class="form-check-label" for="@role">@role</label>
                                    </div>
                                </div>
                            }
                        }

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal" @onclick="Close">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            Save
                        </button>
                    </div>
                </EditForm>
            }
        </div>
    </div>
</div>



@if (_showEditModal)
{
    <div class="modal-backdrop fade show"></div>
}

@code {



    [Parameter]
    public EventCallback<string> OnSaveClick { get; set; }

    private string _modalDisplay = "none;";
    private string _modalClass = "";
    private bool _showEditModal = false;
    private User _item = new User();

    private Dictionary<string, bool> _selectedRoles = new();
    private Dictionary<string, bool> _startingRoles = new();
    private List<IdentityRole> _roles;

    private async Task SaveClick()
    {

        var updateRequest = new UpdateUserRequest()
        {
            User = _item
        };

        await UserManagementService.Update(updateRequest);

        var checkedRoles = _selectedRoles.Where(r => r.Value).Select(r => r.Key).ToList();
        var startingRoles = _startingRoles.Where(r => r.Value).Select(r => r.Key).ToList();

        var rolesToRemove = startingRoles.Except(checkedRoles).ToList();
        var rolesToAdd = checkedRoles.Except(startingRoles).ToList();

        if (rolesToAdd.Any() || rolesToRemove.Any()){
            SaveRolesForUserRequest rolesForUserRequest = new SaveRolesForUserRequest(){
                UserId = _item.Id,
                RolesToAdd = rolesToAdd, 
                RolesToRemove = rolesToRemove
            };

            await UserManagementService.SaveRolesForUser(rolesForUserRequest);
        }

        Logger.LogInformation("Updated User Id: {userId}", _item.Id);
        await OnSaveClick.InvokeAsync(null);
        await Close();
    }

    public async Task Open(string id)
    {
        Logger.LogInformation("Now loading... /Users/Edit/{Id}", id);

        await new Css(JSRuntime).HideBodyOverflow();

        _item = (await UserManagementService.GetById(id)).User;
        _roles = (await RoleManagementService.List()).Roles;
        var userRoles = await UserManagementService.GetRolesByUserId(id);
        foreach (var role in _roles)
        {

            var checkedStatus = userRoles.Roles.Contains(role.Name);
            _selectedRoles[role.Name] = checkedStatus;
            _startingRoles[role.Name] = checkedStatus;
        }

        Logger.LogInformation("Acquired user {id}",_item.Id);

        _modalDisplay = "block;";
        _modalClass = "Show";
        _showEditModal = true;

        StateHasChanged();
    }

    private void UpdateRoleSelectedState(string role, bool isChecked){
        _selectedRoles[role] = isChecked;
    }

    private async Task Close()
    {
        await new Css(JSRuntime).ShowBodyOverflow();

        _modalDisplay = "none";
        _modalClass = "";
        _showEditModal = false;
    }
}
